package com.jxt.mina.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class SessionManage {
	
	private static Logger logger = Logger.getLogger(SessionManage.class);
	/**
	 * 保存sessionid
	 * @param memberId
	 * @param sessionId
	 */
	public void saveSession(String memberId,String sessionId) {
		Connection conn = null; 
		PreparedStatement pstmt = null;
		String sql = "insert into sys_session(member_id,session_id) values(?,?)";
		try {
			conn = DBUtil.conn();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, memberId);
			pstmt.setString(2, sessionId);
			pstmt.executeUpdate();
			conn.commit();
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				logger.error(e1);
			}
			logger.error(e);
		}finally{
			if(pstmt != null){
				try {
					pstmt.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
			
		}
	}
	/**
	 * 删除session
	 * @param sessionId
	 */
	public void delSession(String sessionId){
		Connection conn = null; 
		PreparedStatement pstmt = null;
		String sql = "delete from sys_session where session_id=?";
		try {
			conn = DBUtil.conn();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, sessionId);
			pstmt.executeUpdate();
			conn.commit();
		}catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				logger.error(e1);
			}
			logger.error(e);
		}finally{
			if(pstmt != null){
				try {
					pstmt.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
		}
		
	}
	
	/**
	 * 取得所有的sessionID
	 * @return
	 */
	public List<String> getSessionId(){
		List<String> list = new ArrayList<String>();
		Connection conn = null; 
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select session_id from sys_session";
		try {
			conn = DBUtil.conn();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				String sessionId = rs.getString(1);
				list.add(sessionId);
			}
		}catch (Exception e) {
			logger.error(e);
		}finally{
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
			if(pstmt != null){
				try {
					pstmt.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error(e);
				}
			}
		}
		return list;	
	}
	
}
